local db = {
    users = {},
    cid = {}
    }

function db:init()
    self:load()
    --self:printAllUsers()
    --print(table.save(self.users))
    return self 
end

function db:load()
    local f = io.open("user.db","r")
    local users = bitser.loads(f:read("*a"))
    f:close()
    self.users = users
end

function db:save()
    local f = io.open("user.db","w")
	io.output(f)
	io.write(bitser.dumps(self.users))
	io.close(f)
end

function db:checkAndReg(data,cid)
    if self.users[data.id] then
        return false
    else
        self.users[data.id] = {
            id = data.id,
            password = data.password,
            createTime = os.date("*t", os.time())
        }
        self:save()
        self:login(data,cid)
        print("new id:" .. data.id)
        return self.users[data.id]
    end
end

function db:login(data,cid)
    if self.users[data.id] and self.users[data.id].password == data.password then
        local user = self.users[data.id]
        if user.online == true then
            print("id: "..data.id.." is already online")
            self:logout(user.cid)
            self.cid[cid] = user
            user.online = true
            return user
        else
            self.cid[cid] = user
            user.online = true
            print("id: "..data.id.." login")
            return user
        end
    end
end

function db:logout(cid)
    local user = self.cid[cid]
    if not user then return end
    print("id: "..user.id.." logout")
    user.online = false
    self.cid[cid] = nil
end

function db:logoutAll()
    for cid,user in pairs(self.cid) do
        user.online = false
    end
    self.cid = {}
    print("all user offline")
end

function db:printAllUsers()
    for id , user in pairs(self.users) do
        print(id)
    end
end

function db:getIdByConnect(cid)
    return self.cid[cid] and self.cid[cid].id
end

return db